import configparser
import json
import random
import threading
import time
from collections import defaultdict

from google.protobuf import json_format

import Global
from Script.GameFun import GameFun
from Script.ProtocolMapper import get_message_class_by_id
from Script.protobuf import protocol_pb2


class HandleMsg:
    @staticmethod
    def HandleGameRecvMsg(game_index,msg_id:int,data):
        try:
            Game = Global.G_Game[game_index]
            gameFun = Game.GameFun
            message_class = get_message_class_by_id(msg_id)
            proto = message_class()
            if len(data) > 0:
                proto.ParseFromString(data)
                json_msg = json_format.MessageToJson(proto, indent=None)
                dict_msg = json_format.MessageToDict(proto)
            else:
                json_msg = "{}"
                dict_msg = {}
            if msg_id not in [15029,10510,103]:
                if Global.G_EnableLog:
                    Game.Log.error(f"序号:{game_index},[recv]->功能号:{msg_id},名称:{proto.__class__.__module__.split('.')[-1]}.{proto.__class__.__name__},内容:{json_msg}")


            if msg_id == protocol_pb2.GC_AUTH_LOGIN_ACK:
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.WC_WAITING_NO_VACANCY_NOTI:#WCWaitingNoVacancyNoti
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.GC_GET_WAITING_QUEUE_ORDER_ACK:#GCGetWaitingQueueOrderAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_ACK:#ACGetPlayerAck
                Game.Result = {"code":"ACGetPlayerAck"}
            elif msg_id == protocol_pb2.GC_GET_NMSS_TOKEN_ACK :#GCGetNMSSTokenAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.GC_AUTH_LOGIN_NAK:
                Game.Result = dict_msg

            elif msg_id == protocol_pb2.AC_LOGIN_ACK:
                Game.Result = dict_msg
                Game.Info['login_ack'] =dict_msg
                Game.data['roleName'] =dict_msg.get('AccountName',"")
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INFO_NOTI:
                Game.Info['player']=dict_msg
                Game.data['level'] = dict_msg['AccountLevel']
                LevelRewardStep = Game.Info['player']['LevelRewardStep']
                if LevelRewardStep >0 and Game.data['level'] > LevelRewardStep:
                    Game.GameFun.Req_CALevelUpRewardReq(Game.data['level'])
                heart_thread = threading.Thread(target=HandleMsg.PingThread, args=(game_index,))
                heart_thread.start()
            elif msg_id == protocol_pb2.AC_GET_PLAYER_TICKET_NOTI:
                Game.Info['player_ticket'] = dict_msg['Tickets']
                ticket_info =next((ticket for ticket in dict_msg['Tickets'] if ticket['TicketID'] == 1),None)
                if ticket_info:
                    Game.data['power'] = ticket_info['TicketCount']
            elif msg_id == protocol_pb2.AC_GET_PLAYER_HERO_NOTI:
                Game.Info['player_hero'] = dict_msg['Heros']
            elif msg_id == protocol_pb2.AC_GET_PLAYER_FORMATION_NOTI:#ACGetPlayerFormationNoti
                Game.Info['player_formation'] = dict_msg['Formations']
            elif msg_id == protocol_pb2.AC_FORMATION_LEVEL_UP_ACK:#ACFormationLevelUpAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_STAGE_NOTI:
                Game.Info['player_stage'] = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_REPETITION_BATTLE_NOTI:#ACGetPlayerRepetitionBattleNoti
                Game.Info['repetition_battle'] = dict_msg
            elif msg_id == protocol_pb2.AC_REPETITION_BATTLE_ENTER_STAGE_ACK:
                Game.Result = dict_msg
                Game.isRepetition_Battle = True
            elif msg_id == protocol_pb2.AC_REPETITION_BATTLE_ENTER_STAGE_NAK:#ACRepetitionBattleEnterStageNak
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_USER_OPTION_NOTI:
                Game.Info['player_user_option'] = dict_msg['HeroReinforces']
            elif msg_id == protocol_pb2.AC_INDIVIDUAL_MISSION_REWARD_ACK:#ACIndividualMissionRewardAck
                Game.Result =dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INDIVIDUAL_MISSION_NOTI:#ACGetPlayerIndividualMissionNoti
                Game.Info['individual_mission'] = dict_msg
            elif msg_id == protocol_pb2.AC_CHANGE_INDIVIDUAL_MISSION_NOTI:#ACChangeIndividualMissionNoti
                Mission_list = dict_msg.get("ChangeIndividualMission", None)
                if not Game.Info.get('individual_mission',None):
                    Game.Info['individual_mission']={'Mission':[],'NextDailyRenewalTimeMS':0}
                if not Game.Info['individual_mission'].get('Mission',None):
                    Game.Info['individual_mission']['Mission']=[]
                if Mission_list:
                    for mission in Mission_list:
                        cur_mission= next((mission_info for mission_info in Game.Info['individual_mission']['Mission'] if mission_info['MissionID'] == mission['MissionID']),None)
                        if cur_mission:
                            cur_mission.update(mission)
                        else:
                            Game.Info['individual_mission']['Mission'].append(mission)
                Game.Info['individual_mission']['"NextDailyRenewalTimeMS"']=dict_msg.get("NextDailyRenewalTimeMS", None)
            elif msg_id == protocol_pb2.AC_PLAYER_GUIDE_QUEST_NOTI:#ACPlayerGuideQuestNoti
                Game.Info['guide_mission'] =dict_msg
            elif msg_id == protocol_pb2.AC_GUIDE_QUEST_MISSION_REWARD_ACK:#ACGuideQuestMissionRewardAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_CHANGE_GUIDE_QUEST_NOTI:#ACChangeGuideQuestNoti
                ChangedGuideQuestList = dict_msg.get('ChangedGuideQuestList',[])
                for change_guide in ChangedGuideQuestList:
                    if not Game.Info['guide_mission'].get('GuideQuestList', None):
                        Game.Info['guide_mission']['GuideQuestList'] = []
                    cur_guide = next((guide for guide in Game.Info['guide_mission']['GuideQuestList'] if guide.get('EventMainTID',0) == change_guide['EventMainTID']),None)
                    if cur_guide:
                        cur_guide.update(change_guide)
                    else:
                        Game.Info['guide_mission']['GuideQuestList'].append(change_guide)
                Missions = dict_msg.get('Missions', [])
                for change_mission in Missions:
                    if not Game.Info['guide_mission'].get('Missions', None):
                        Game.Info['guide_mission']['Missions'] = []
                    cur_mission = next((mission for mission in Game.Info['guide_mission']['Missions'] if mission.get('MissionID',0) == change_mission['MissionID']), None)
                    if cur_mission:
                        cur_mission.update(change_mission)
                    else:
                        Game.Info['guide_mission']['Missions'].append(change_mission)
            elif msg_id == protocol_pb2.AC_EVENT_MISSION_REWARD_ACK:#ACEventMissionRewardAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_PLAYER_EVENT_MISSION_NOTI:#ACPlayerEventMissionNoti
                Game.Info['event_mission'] =dict_msg.get('Missions',[])
            elif msg_id == protocol_pb2.AC_CHANGE_EVENT_MISSION_NOTI:#ACChangeEventMissionNoti
                Mission_list = dict_msg.get("ChangedMissions", None)
                if Mission_list:
                    if not Game.Info.get('event_mission',None):
                        Game.Info['event_mission']=[]
                    for mission in Mission_list:
                        MissionID = mission['MissionID']
                        cur_mission =next((mission_info for mission_info in Game.Info['event_mission'] if mission_info['MissionID'] == MissionID),None)
                        if cur_mission:
                            cur_mission.update(mission)
                        else:
                            Game.Info['event_mission'].append(mission)
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INVENTORY_WEAPON_NOTI:#ACGetPlayerInventoryWeaponNoti 武器
                EquipItems =dict_msg.get('EquipItems', [])
                Game.Info['inventory_weapon'] =EquipItems
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INVENTORY_ARMOR_NOTI:#ACGetPlayerInventoryArmorNoti  护甲
                EquipItems =dict_msg.get('EquipItems', [])
                Game.Info['inventory_armor'] =EquipItems
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INVENTORY_ACCESSORY_NOTI:#ACGetPlayerInventoryAccessoryNoti  戒指
                EquipItems =dict_msg.get('EquipItems', [])
                Game.Info['inventory_accessory'] =EquipItems
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INVENTORY_CONSUMABLE_NOTI:  # ACGetPlayerInventoryConsumableNoti 消耗品
                StackItems = dict_msg.get('StackItems', [])
                Game.Info['inventory_consumable'] = StackItems
            elif msg_id == protocol_pb2.AC_GET_PLAYER_INVENTORY_MATERIAL_NOTI:  # ACGetPlayerInventoryMaterialNoti 材料
                StackItems = dict_msg.get('StackItems', [])
                Game.Info['inventory_meterial'] = StackItems
            elif msg_id == protocol_pb2.AC_OPEN_ITEM_BOX_ACK:#ACOpenItemBoxAck
                Game.Result =dict_msg
            elif msg_id == protocol_pb2.AC_CHANGE_ITEM_NOTI:#ACChangeItemNoti  消耗品变化
                ChangeStackItems =dict_msg.get('ChangeStackItems',None)
                if ChangeStackItems:
                    for change_item in ChangeStackItems:
                        isFind = False
                        Category =int(change_item['ItemType']//100)
                        if not Game.Info.get('inventory_consumable', None):
                            Game.Info['inventory_consumable'] = []
                        if Category == 2:#消耗品
                            for item_info in Game.Info['inventory_consumable']:
                                if item_info['ItemUniqueID'] == change_item['ItemUniqueID']:
                                    item_info.update(change_item)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['inventory_consumable'].append(change_item)
                        elif Category == 3:#材料
                            if not Game.Info.get('inventory_meterial', None):
                                Game.Info['inventory_meterial'] = []
                            for item_info in Game.Info['inventory_meterial']:
                                if item_info['ItemUniqueID'] == change_item['ItemUniqueID']:
                                    item_info.update(change_item)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['inventory_meterial'].append(change_item)
                ChangeEquipItems = dict_msg.get('ChangeEquipItems', None)
                if ChangeEquipItems:
                    for change_item in ChangeEquipItems:
                        isFind = False
                        if not Game.Info.get('inventory_weapon', None):
                            Game.Info['inventory_weapon'] = []
                        if change_item['ItemType'] == 101:#武器
                            for item_info in Game.Info['inventory_weapon']:
                                if item_info['ItemUniqueID'] == change_item['ItemUniqueID']:
                                    item_info.update(change_item)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['inventory_weapon'].append(change_item)
                        elif change_item['ItemType'] == 103:#铠甲
                            if not Game.Info.get('inventory_armor', None):
                                Game.Info['inventory_armor'] = []
                            for item_info in Game.Info['inventory_armor']:
                                if item_info['ItemUniqueID'] == change_item['ItemUniqueID']:
                                    item_info.update(change_item)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['inventory_armor'].append(change_item)
                        elif change_item['ItemType'] == 102:#戒指  这里暂时没有需要验证
                            if not Game.Info.get('inventory_accessory', None):
                                Game.Info['inventory_accessory'] = []
                            for item_info in Game.Info['inventory_accessory']:
                                if item_info['ItemUniqueID'] == change_item['ItemUniqueID']:
                                    item_info.update(change_item)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['inventory_accessory'].append(change_item)
                RemoveItemUIDs = dict_msg.get('RemoveItemUIDs', None)
                if RemoveItemUIDs:
                    for item_id in RemoveItemUIDs:
                        Game.Info['inventory_consumable']=list(filter(lambda item: item["ItemUniqueID"] != item_id, Game.Info['inventory_consumable']))
                        Game.Info['inventory_meterial'] = list(filter(lambda item: item["ItemUniqueID"] != item_id, Game.Info['inventory_meterial']))
            elif msg_id == protocol_pb2.AC_GET_PLAYER_CONTENTS_UNLOCK_NOTI:#ACGetPlayerContentsUnlockNoti
                Game.Info['player_contents'] = dict_msg['ContentsUnlockInfos']
            elif msg_id == protocol_pb2.AC_CONTENTS_UNLOCK_ACK:#CAContentsUnlockReq
                ContentsUnlockInfos = dict_msg.get('ContentsUnlockInfos', None)
                if ContentsUnlockInfos:
                    for content_unlock in ContentsUnlockInfos:
                        isFind = False
                        for hero_info in Game.Info['player_contents']:
                            if hero_info['ContentsID'] == content_unlock['ContentsID']:
                                hero_info.update(content_unlock)
                                isFind = True
                                break
                        if not isFind:
                            Game.Info['player_contents'].append(content_unlock)
                Game.Result =dict_msg
            elif msg_id == protocol_pb2.AC_CONTENTS_UNLOCK_CHANGE_NOTI:
                ContentsUnlockInfos = dict_msg.get('ContentsUnlockInfos',None)
                if ContentsUnlockInfos:
                    for content_unlock in ContentsUnlockInfos:
                        isFind = False
                        for hero_info in Game.Info['player_contents']:
                            if hero_info['ContentsID'] == content_unlock['ContentsID']:
                                hero_info.update(content_unlock)
                                isFind = True
                                break
                        if not isFind:
                            Game.Info['player_contents'].append(content_unlock)
            elif msg_id == protocol_pb2.AC_CHANGE_PLAYER_NICKNAME_ACK:
                Game.Result = dict_msg
                NickName =dict_msg.get('NickName', "")
                Game.Info['login_ack']["AccountName"] =NickName
                Game.data['roleName'] =NickName
            elif msg_id == protocol_pb2.AC_PLAYER_GACHA_NOTI:#抽卡
                Game.Info['player_gacha'] = dict_msg['GachaList']
            elif msg_id == protocol_pb2.AC_GET_PLAYER_TUTORIAL_NOTI:
                Game.Info['player_tutorial'] = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_ETC_NOTI:#ACGetPlayerEtcNoti
                Game.Info['player_etc'] =dict_msg['Etcs']
                Game.data['diamond'] = HandleMsg.取_货币数量(game_index,501)
                Game.data['gold'] = HandleMsg.取_货币数量(game_index, 502)
                Game.data['money'] = HandleMsg.取_货币数量(game_index, 508)
            elif msg_id == protocol_pb2.AC_GET_PLAYER_DECK_NOTI:#ACGetPlayerDeckNoti
                Game.Info['player_deck'] = dict_msg
            elif msg_id == protocol_pb2.AC_SAVE_PLAYER_DECK_ACK:#ACSavePlayerDeckAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_CHANGE_PLAYER_DECK_NOTI:#ACChangePlayerDeckNoti
                if not Game.Info.get('player_deck',None):
                    Game.Info['player_deck']={'Decks':[]}
                for deck in dict_msg['Decks']:
                    cur_deck_info =next((deck_info for deck_info in Game.Info['player_deck']['Decks'] if deck_info.get('DeckType',0) == deck['DeckType']),None)
                    if cur_deck_info:
                        cur_deck_info.update(deck)
                    else:
                        Game.Info['player_deck']['Decks'].append(deck)
            elif msg_id == protocol_pb2.AC_GET_HERO_FIRST_TALK_NOTI:
                Game.Info['hero_first_talk'] = dict_msg
                Game.Result = {"code":"LoadOk"}
                Game.isInit =True
            elif msg_id == protocol_pb2.AC_TUTORIAL_START_ACK:#ACTutorialStartAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_TUTORIAL_END_ACK:#ACTutorialEndAck
                Game.Result = dict_msg
                if not Game.Info['player_tutorial'].get("Tutorial",{}):
                    Game.Info['player_tutorial']={"Tutorial":[dict_msg['Tutorials'][0]]}
                else:
                    TutorialID = dict_msg['Tutorials'][0]['TutorialID']
                    Status = dict_msg['Tutorials'][0]['Status']
                    tutorial_info = next((item for item in Game.Info['player_tutorial']['Tutorial'] if item['TutorialID']==TutorialID),None)
                    if tutorial_info:
                        tutorial_info["Status"] = Status
                    else:
                        Game.Info['player_tutorial']['Tutorial'].append(dict_msg['Tutorials'][0])
            elif msg_id == protocol_pb2.AC_CHANGE_TICKET_NOTI:#
                change_Tickets = dict_msg['Tickets']
                for change_ticket in change_Tickets:
                    isFind = False
                    if change_ticket['TicketID'] ==1:
                        Game.data['power']=change_ticket['TicketCount']
                    player_ticket =Game.Info.get('player_ticket',None)
                    if player_ticket:
                        for ticket_info in player_ticket:
                            if ticket_info['TicketID'] == change_ticket['TicketID']:
                                ticket_info.update(change_ticket)
                                isFind = True
                                break
                    else:
                        Game.Info['player_ticket'] =[]
                    if not isFind:
                        Game.Info['player_ticket'].append(change_ticket)

            elif msg_id == protocol_pb2.AC_COMMON_NAK:#ACCommonNak
                Error = dict_msg.get('Error',None)
                if Error:
                    if Error=="E_DUPLICATE_CONNECTION":
                        Global.LOGE(game_index,f"[通讯]->账号已在其他地方登陆")
                        return
                    if Error== "E_NOT_OPENED_REGIEON":
                        Global.LOGE(game_index, f"[通讯]->暂不支持该国家")
                        Game.Game.Close()
                        return
                    Global.LOGE(game_index,f"[错误]->{Error},消息ID：{dict_msg.get('SuccessfulMsgId',0)}")
                #if Error and Error == protocol_pb2.E_WRONG_PLAYER_DATA_CLIENT_RECONNECT:
                if proto.Error !=protocol_pb2.E_NOT_UNLOCKED_CONTENTS and proto.Error != protocol_pb2.E_DUPLICATE_CLIENT:#and proto.Error!= protocol_pb2.E_MISSION_REWARD_BY_NOT_COMPLETE_MISSION
                    Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_MAILLIST_ACK:#ACGetMailListAck
                Game.Info['mail'] = dict_msg
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_MAIL_READ_ALL_ACK:
                ReadMailUniqueIDs =dict_msg['ReadMailUniqueIDs']
                for mail_id in ReadMailUniqueIDs:
                    Game.Info['mail']['Mails'] = list(filter(lambda mail: mail["MailID"] != mail_id, Game.Info['mail']['Mails']))
                    Game.Info['mail']['TotalMailCount'] = Game.Info['mail']['TotalMailCount'] -1
                ResultReward = dict_msg.get('ResultReward',None)
                if ResultReward:
                    Etcs =ResultReward.get('Etcs',None)
                    if Etcs:
                        for change_etc in Etcs:
                            isFind = False
                            for etc_info in Game.Info['player_etc']:
                                if etc_info['ID'] == change_etc['ID']:
                                    etc_info.update(change_etc)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['player_etc'].append(change_etc)
                        Game.data['diamond'] = HandleMsg.取_货币数量(game_index, 501)
                        Game.data['gold'] = HandleMsg.取_货币数量(game_index, 502)
                        Game.data['money'] = HandleMsg.取_货币数量(game_index, 508)
                    Tickets = ResultReward.get('Tickets', None)
                    if Tickets:
                        for change_ticket in Tickets:
                            isFind = False
                            if change_ticket['TicketID'] == 1:
                                Game.data['power'] = change_ticket['TicketCount']
                            for ticket_info in Game.Info['player_ticket']:
                                if ticket_info['TicketID'] == change_ticket['TicketID']:
                                    ticket_info.update(change_ticket)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['player_ticket'].append(change_ticket)
                    Heros = ResultReward.get('Heros', None)
                    if Heros:
                        for change_hero in Heros:
                            isFind = False
                            for hero_info in Game.Info['player_hero']:
                                if hero_info['HeroUid'] == change_hero['HeroUid']:
                                    hero_info.update(change_hero)
                                    isFind = True
                                    break
                            if not isFind:
                                Game.Info['player_hero'].append(change_hero)
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_MAIL_DELETE_ALL_ACK:#ACMailDeleteAllAck
                Game.Result={"code":"success"}
            elif msg_id == protocol_pb2.AC_ENTER_STAGE_ACK:#ACEnterStageAck
                Game.Result = dict_msg
                Game.Info['battle'] =dict_msg
                Game.isInBattle = True
            elif msg_id == protocol_pb2.AC_ENTER_STAGE_NAK:#ACEnterStageNak
                Game.Result = dict_msg
                Game.isInBattle = False
            elif msg_id == protocol_pb2.AC_BATTLE_DECK_NOTI:
                if not Game.isRepetition_Battle:
                    gameFun.Req_CAReadyStageReq() #准备
            elif msg_id == protocol_pb2.AC_READY_STAGE_ACK:#ACReadyStageAck
                if not Game.isRepetition_Battle:
                    gameFun.Req_CAQuickAnimationReq(True)
                    gameFun.Req_CAAutoSkillReq(True)  # 自动技能
                    gameFun.Req_CAPlaySpeedReq(True)
                gameFun.Req_CAStartStageReq()  #开始关卡
            elif msg_id == protocol_pb2.AC_QUICK_ANIM_ACK:
                pass
            elif msg_id == protocol_pb2.AC_STATUS_EFFECT_NOTI:
                gameFun.Req_CAStartRoundReq()
            elif msg_id == protocol_pb2.AC_START_STAGE_ACK:
                pass
            elif msg_id == protocol_pb2.AC_ATTACK_SEQUENCE_NOTI:
                if Game.isInBattle:
                    Global.LOGD(game_index,f"[关卡]->战斗中,ID:{Game.Info['battle']['StageId']},第{dict_msg['Round']}波")
            elif msg_id == protocol_pb2.AC_END_STAGE_NOTI:#ACEndStageNoti
                Game.isInBattle = False
                Game.Result = dict_msg
                #Stage = Game.Info['player_stage'].get('Stage',None)
                Game.Info['player_stage']['Stage']= dict_msg['StageRecord']
                StageResults = Game.Info['player_stage'].get('StageResults', None)
                if not StageResults:
                    Game.Info['player_stage']['StageResults'] = []
                    Game.Info['player_stage']['StageResults'].append(dict_msg['StageResult'])
                else:
                    isFind = False
                    for stage_result in Game.Info['player_stage']['StageResults']:
                        if stage_result['StageId'] == dict_msg['StageResult']['StageId']:
                            stage_result.update(dict_msg['StageResult'])
                            isFind = True
                            break
                    if not isFind:
                        Game.Info['player_stage']['StageResults'].append(dict_msg['StageResult'])
            elif msg_id == protocol_pb2.AC_CHANGE_ACCOUNT_LEVEL_NOTI:#ACChangeAccountLevelNoti 等级变动
                Game.data['level'] = dict_msg['AccountLevel']
                Game.Info['player']['AccountLevel']=dict_msg['AccountLevel']
                Game.Info['player']['AccountExp'] = dict_msg['AccountExp']
                LevelRewardStep = Game.Info['player']['LevelRewardStep']
                if LevelRewardStep >0 and Game.data['level'] > LevelRewardStep:
                    Game.GameFun.Req_CALevelUpRewardReq(Game.data['level'])
            elif  msg_id == protocol_pb2.AC_LEVELUP_REWARD_ACK:#ACLevelUpRewardAck
                LevelRewardStep = dict_msg.get('LevelRewardStep',0)
                Game.Info['player']['LevelRewardStep'] = LevelRewardStep
                if LevelRewardStep >0 and Game.data['level'] > LevelRewardStep:
                    Game.GameFun.Req_CALevelUpRewardReq(Game.data['level'])
            elif msg_id == protocol_pb2.AC_GET_PLAYER_COLLECTION_BOOK_ACK:#ACGetPlayerCollectionBookAck
                Game.Info['player_book'] = dict_msg
            elif msg_id == protocol_pb2.AC_COLLECTION_BOOK_REWARD_ACK:
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_ADD_COLLECTION_BOOK_NOTI:#ACAddCollectionBookNoti
                HeroCollectionBook = dict_msg.get("HeroCollectionBook", [])
                for book_info in HeroCollectionBook:
                    if not Game.Info['player_book'].get('HeroCollectionBook', None):
                        Game.Info['player_book']['HeroCollectionBook']=[]
                    cur_collection_book = next((collection_book for collection_book in Game.Info['player_book']['HeroCollectionBook'] if collection_book['GroupTID'] == book_info['GroupTID']),None)
                    if cur_collection_book:
                        cur_collection_book.update(book_info)
                    else:
                        Game.Info['player_book']['HeroCollectionBook'].append(book_info)
                PetCollectionBook = dict_msg.get("PetCollectionBook", [])
                for book_info in PetCollectionBook:
                    if not Game.Info['player_book'].get('PetCollectionBook', None):
                        Game.Info['player_book']['PetCollectionBook'] = []
                    cur_collection_book = next((collection_book for collection_book in Game.Info['player_book']['PetCollectionBook'] if collection_book['GroupTID'] == book_info['GroupTID']), None)
                    if cur_collection_book:
                        cur_collection_book.update(book_info)
                    else:
                        Game.Info['player_book']['PetCollectionBook'].append(book_info)
                ItemCollectionBook = dict_msg.get("ItemCollectionBook", [])
                for book_info in ItemCollectionBook:
                    if not Game.Info['player_book'].get('ItemCollectionBook', None):
                        Game.Info['player_book']['ItemCollectionBook'] = []
                    cur_collection_book = next((collection_book for collection_book in Game.Info['player_book']['ItemCollectionBook'] if collection_book['GroupTID'] == book_info['GroupTID']), None)
                    if cur_collection_book:
                        cur_collection_book.update(book_info)
                    else:
                        Game.Info['player_book']['ItemCollectionBook'].append(book_info)
            elif msg_id == protocol_pb2.AC_CHANGE_ETC_NOTI:#金币变化
                change_Etcs = dict_msg['Etcs']
                for change_etc in change_Etcs:
                    isFind = False
                    for etc_info in Game.Info['player_etc']:
                        if etc_info['ID'] == change_etc['ID']:
                            etc_info.update(change_etc)
                            isFind =True
                            break
                    if not isFind:
                        Game.Info['player_etc'].append(change_etc)
                Game.data['diamond'] = HandleMsg.取_货币数量(game_index, 501)
                Game.data['gold'] = HandleMsg.取_货币数量(game_index, 502)
                Game.data['money'] = HandleMsg.取_货币数量(game_index, 508)
            elif msg_id == protocol_pb2.AC_CHANGE_HERO_NOTI:#ACChangeHeroNoti
                change_heros = dict_msg.get('Heros',[])
                for change_hero in change_heros:
                    isFind = False
                    for hero_info in Game.Info['player_hero']:
                        if hero_info['HeroUid'] == change_hero['HeroUid']:
                            hero_info.update(change_hero)
                            isFind = True
                            break
                    if not isFind:
                        Game.Info['player_hero'].append(change_hero)
                RemoveHeroUIDs = dict_msg.get('RemoveHeroUIDs', [])
                for chage_id in RemoveHeroUIDs:
                    Game.Info['player_hero'] = list(filter(lambda hero: hero["HeroUid"] != chage_id, Game.Info['player_hero']))
            elif msg_id == protocol_pb2.AC_GET_GACHA_ACK:#ACGetGachaAck
                Game.Info['player_gacha'] = dict_msg['GachaList']
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_GACHA_ACK:
                Game.Info['player_gacha']= dict_msg['GachaList']
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_CHANGE_GACHA_NOTI:
                ChangedGachaList = dict_msg.get('ChangedGachaList',None)
                if ChangedGachaList:
                    if not Game.Info.get('player_gacha',None):
                        Game.Info['player_gacha'] = []
                    for change_gacha in ChangedGachaList:
                        isFind = False
                        for gacha_info in Game.Info['player_gacha']:
                            if gacha_info['GachaTID'] == change_gacha['GachaTID']:
                                gacha_info.update(change_gacha)
                                isFind = True
                                break
                        if not isFind:
                            Game.Info['player_gacha'].append(change_gacha)
                    ExpiredGachaTIDs = dict_msg.get('ExpiredGachaTIDs', None)
                    if ExpiredGachaTIDs:
                        for chage_id in ExpiredGachaTIDs:
                            Game.Info['player_gacha'] =list(filter(lambda item: item["GachaTID"] != chage_id, Game.Info['player_gacha']))
            elif msg_id == protocol_pb2.AC_DRAW_GACHA_ACK:#ACDrawGachaAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_SET_PRE_ORDER_SKILL_ACK:
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_OPEN_ITEM_BOX_ACK:#ACOpenItemBoxAck
                Tickets =dict_msg['ResultReward'].get('Tickets',[])
                for change_ticket in Tickets:
                    isFind = False
                    if change_ticket['TicketID'] ==1:
                        Game.data['power']=change_ticket['TicketCount']
                    for ticket_info in Game.Info['player_ticket']:
                        if ticket_info['TicketID'] == change_ticket['TicketID']:
                            ticket_info.update(change_ticket)
                            isFind = True
                            break
                    if not isFind:
                        Game.Info['player_ticket'].append(change_ticket)
                Heros = dict_msg['ResultReward'].get('Heros', [])
                for hero_info in Heros:
                    player_hero =Game.Info.get('player_hero',[])
                    cur_hero = next((hero for hero in player_hero if hero.get('HeroUid',0) == hero_info['HeroUid']),None)
                    if cur_hero:
                        cur_hero.update(hero_info)
                    else:
                        Game.Info['player_hero'].append(hero_info)
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_LEAVE_STAGE_ACK:#ACLeaveStageAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_HERO_EQUIP_ITEM_ACK :#ACHeroEquipItemAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_ITEM_REINFORCE_ACK :#ACItemReinforceAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_REPETITION_BATTLE_RESULT_ACK:#ACRepetitionBattleResultACK
                Game.Result = {"code":"return_OK"}
            elif msg_id == protocol_pb2.AC_REPETITION_BATTLE_RESULT_NOTI:#ACRepetitionBattleResultNoti
                Game.Info['repetition_battle'] = dict_msg
                ProcessState = dict_msg['BattleInfo']['ProcessState']
                if ProcessState < 3:
                    Game.isRepetition_Battle = True
            elif msg_id == protocol_pb2.AC_REPETITION_BATTLE_ONE_PLAY_RESULT_NOTI:#ACRepetitionBattleOnePlayResultNoti
                BattleCount=dict_msg['BattleCount']
                MaxBattleCount = dict_msg['MaxBattleCount']
                StageId =dict_msg['StageResult']['StageId']
                CompleteStar = dict_msg['StageResult']['CompleteStar']
                Global.LOGD(game_index,f"[重复关卡]->当前进度:{BattleCount}/{MaxBattleCount},关卡:{StageId},星级:{CompleteStar}")

            elif msg_id == protocol_pb2.AC_RELAY_SHOP_INFO_NOTI:#ACRelayShopInfoNoti
                Game.Info['relay_shop']=dict_msg['RelayShop']
            elif msg_id == protocol_pb2.AC_BUY_SHOP_GOODS_ACK:#ACBuyShopGoodsAck
                Game.Result =dict_msg
            elif msg_id == protocol_pb2.AC_CONDITION_GOODS_ACK:#ACConditionGoodsAck
                Game.Info['condition_goods'] = dict_msg['Goods']
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_SHOP_ACK:#ACGetShopAck
                Game.Info['shop'] = dict_msg['Shops']
                Game.Result=dict_msg
            elif msg_id == protocol_pb2.AC_RECEIVE_BATTLE_PASS_REWARD_ACK:#ACReceiveBattlePassRewardAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_GET_PLAYER_BATTLE_PASS_NOTI:#ACGetPlayerBattlePassNoti
                Game.Info['battle_pass']=dict_msg
            elif msg_id == protocol_pb2.AC_CHANGED_PLAYER_BATTLE_PASS_NOTI:#ACChangedPlayerBattlePassNoti
                UpdatedBattlePasses = dict_msg.get('UpdatedBattlePasses',[])
                if not Game.Info.get('battle_pass', None):
                    Game.Info['battle_pass'] = {"BattlePasses": [], "Missions": []}
                if not Game.Info['battle_pass'].get("BattlePasses", None):
                    Game.Info['battle_pass']["BattlePasses"] = []
                for change_battlepass in UpdatedBattlePasses:
                    EventMainTID = change_battlepass['EventMainTID']
                    cur_battlepass = next((battlepass for battlepass in Game.Info['battle_pass']["BattlePasses"] if battlepass.get('EventMainTID',0) == EventMainTID),None)
                    if cur_battlepass:
                        cur_battlepass.update(change_battlepass)
                    else:
                        Game.Info['battle_pass']["BattlePasses"].append(change_battlepass)
                DeletedEventMainTIDs = dict_msg.get('DeletedEventMainTIDs', [])
                for mainid in DeletedEventMainTIDs:
                    Game.Info['battle_pass']["Missions"] =list(filter(lambda item: item["MissionID"] != mainid, Game['battle_pass']["Missions"]))
            elif msg_id == protocol_pb2.AC_CHANGED_PLAYER_BATTLE_PASS_MISSION_NOTI:#ACChangedPlayerBattlePassMissionNoti
                Missions = dict_msg.get('Missions', [])
                for change_mission in Missions:
                    MissionID = change_mission['MissionID']
                    if not Game.Info.get('battle_pass', None):
                        Game.Info['battle_pass'] = {"BattlePasses": [], "Missions": []}
                    if Game.Info['battle_pass'].get("BattlePasses",None):
                        Game.Info['battle_pass']["BattlePasses"]=[]
                    if Game.Info['battle_pass'].get("Missions",None):
                        Game.Info['battle_pass']["Missions"]=[]
                    cur_mission = next((mission for mission in Game.Info['battle_pass'].get("Missions",[]) if mission['MissionID'] == MissionID), None)
                    if cur_mission:
                        cur_mission.update(change_mission)
                    else:
                        Game.Info['battle_pass']["BattlePasses"].append(change_mission)
                DeletedEventMainTIDs = dict_msg.get('DeletedEventMainTIDs', [])
                for mainid in DeletedEventMainTIDs:
                    Game.Info['battle_pass']["Missions"] = list(filter(lambda item: item["MissionID"] != mainid, Game.Info['battle_pass']["Missions"]))
            elif msg_id == protocol_pb2.AC_HERO_REINFORCE_ACK:#ACHeroReinforceAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_STAGE_ACHIEVEMENT_REWARD_ACK:#ACStageAchievementRewardAck
                StarAchievementIDs =Game.Info['player_stage'].get('StarAchievementIDs',[])
                recv_StarAchievementIDs= dict_msg['StarAchievementIDs']
                for id in recv_StarAchievementIDs:
                    StarAchievementIDs.append(id)
                Game.Result =dict_msg
            elif msg_id == protocol_pb2.AC_HERO_COMPOSE_ACK:
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_CONVERSION_ACK:#ACConversionAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_HERO_EVOLUTION_ACK:#ACHeroEvolutionAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_HERO_FIRST_TALK_ACK:#ACHeroFirstTalkAck
                Game.Result = dict_msg
            elif msg_id == protocol_pb2.AC_AGIT_TALK_HERO_ACK:#ACAgitTalkHeroAck
                Game.Result = {"code":"talk ok"}
            elif msg_id == protocol_pb2.AC_ACCUMULATE_PURCHASE_REWARD_ACK:#ACAccumulatePurchaseRewardAck
                Game.Result = {"code": "purchase ok"}
            elif msg_id == protocol_pb2.AC_ACCUMULATE_PURCHASE_NOTI:#ACAccumulatePurchaseNoti
                Game.Info['purchase']=dict_msg.get("Info",{})

        except Exception as e:
            Global.LOGE(game_index,f"[异常]->HandleGameRecMsg:{e},msg_id:{msg_id}")


    @staticmethod
    def PingThread(index):
        if index > -1:
            Game = Global.G_Game[index]
        else:
            Game = Global.G_BindGame
        start_time = time.time()
        while Game.Game.connected:
            end_time = time.time()
            Game.GameFun.Req_NetAliveReq()
            time.sleep(5)
            if not Game.Game:
                break

    @staticmethod
    def 取_货币数量(index,id):
        if index == -1:
            return 0
        player_etc =Global.G_Game[index].Info['player_etc']
        return next((currency['Value'] for currency in player_etc if currency['ID']==id),0)
    @staticmethod
    def 取卡片配置信息(dbc_name,id):
        dbc_list = Global.G_Dbc.get(dbc_name, None)
        if not dbc_list:
            return None
        return next((dbc for dbc in dbc_list if dbc['TID'] == id), None)